package com.howso.cloud.uaa.granter;

import com.howso.cloud.oauth2.token.MobileSmsAuthenticationToken;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 手机+短信验证码模式登录
 */
public class MobileSmsGranter extends AbstractTokenGranter {
    private static final String GRANT_TYPE = "mobile_sms";

    private final AuthenticationManager authenticationManager;


    public MobileSmsGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices
                    , ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
        super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
        this.authenticationManager = authenticationManager;
    }


    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
        String mobile = parameters.get("mobile");
        String sms = parameters.get("sms");
        // Protect from downstream leaks of password
        parameters.remove("sms");
        if(StringUtils.isAllEmpty(mobile,sms)){
            throw new InvalidGrantException("the mobile and sms can't be null" );
        }
        Authentication userAuth = new MobileSmsAuthenticationToken(mobile, sms);
        ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
        userAuth = authenticationManager.authenticate(userAuth);
        if (userAuth == null || !userAuth.isAuthenticated()) {
            throw new InvalidGrantException("Could not authenticate mobile: " + mobile);
        }

        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
        return new OAuth2Authentication(storedOAuth2Request, userAuth);
    }
}
